#ifndef A8_HTTPITEM_H
#define A8_HTTPITEM_H

#include <a8/_socketitem.hpp>

namespace a8
{

	const int MAX_HTTP_REUEST = 1024 * 2;

	class HttpSocketItem : public ClientSocketItem
	{
	public:

		virtual void Initialize()
		{
			mCreateTime = time(NULL);
			mHandled = false;
			mRecvBuff = (char *)malloc(MAX_HTTP_REUEST + 2);
			mRecvBuffLen = 0;
		}

		virtual void Finalize()
		{
			mHandled = false;
			free(mRecvBuff);
			mRecvBuff = NULL;
			mRecvBuffLen = 0;
		}

		virtual void OnSocketRead(char* buf, unsigned int buflen)
		{
			if(mRecvBuffLen + buflen > MAX_HTTP_REUEST){
				g_udplog->Warning("receive to long http package %d", (long long)mRecvBuffLen + buflen);
				return;
			}
			memmove(&mRecvBuff[mRecvBuffLen], buf, buflen);
			mRecvBuffLen += buflen; 
			mRecvBuff[mRecvBuffLen] = '\0';
			char* p_header_end = strstr(mRecvBuff, "\r\n\r\n");
			if(p_header_end && !mHandled){
				mHandled = true;
				if(strncmp(mRecvBuff, "GET ", strlen("GET ")) == 0){
					std::string uri;
					for(int i = 4; i < mRecvBuffLen; i++){
						if(mRecvBuff[i] == ' '){
							break;
						}
						uri.push_back(mRecvBuff[i]);
					}//end for
					std::string response;
					std::string querystr;
					{
						int ipos = uri.find('?');
						if(ipos != std::string::npos){
							querystr = uri.substr(ipos + 1);
						}
					}
					if(querystr.size() > 0){
						unsigned long reqid = g_gmmhandler->AddGMMsg(querystr.c_str());
						response = g_gmmhandler->WaitForGMMsg(reqid,200);
					}
					{
						std::string http_header = a8::format( 
															 "HTTP/1.1 200 OK\r\n"
															 "Content-Type: text/plain\r\n"
															 "Content-Length: %d\r\n\r\n%s",
															 (long long)response.size(), 
															 response);
						g_httplistener->SendClientMsg(mSocketHandle, http_header.c_str(), http_header.size());
					}
				}
			}
		}

	private:
		time_t mCreateTime;
		bool mHandled;
		char *mRecvBuff;
		unsigned int mRecvBuffLen;
	};

}

#endif
